var wx = require("weixin-js-sdk");
import api from "./api";
// 随机字符串
function randomString(len) {
  len = len || 32;
  var $chars =
    "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = "";
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}


var getWeixincofig = function(data) {
  let url = location.href.split("#")[0];
  let nonceStr =  randomString(32);
  let parameter = `?nonceStr=${nonceStr}&timestamp=${data.timestamp}&url=${url}`;
  // console.log(parameter);
  api.get(
    "/exh/v1/jsSdkSign" + parameter ,
    {},
    s => {
      console.log(s);
      shareweixin(s, data,nonceStr);
    },
    f => {},
    {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "*/*"
    }
  );
};

function shareweixin(s,config,nonceStr) {
  wx.config({
    debug: false,
    appId: "wxc1ef1c64f25053dc",
    timestamp: config.timestamp,
    nonceStr: nonceStr,
    signature: s.module,
    jsApiList: [
      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'onMenuShareQQ',
      'onMenuShareWeibo',
      'onMenuShareQZone'
    ]
  });
  console.log(config.timestamp, s.module);
  wxShare(config);
}

function wxShare(config) {
  //检测api是否生效
  wx.ready(function() {
    // wx.checkJsApi({
    //   jsApiList: ["getNetworkType", "previewImage"],
    //   success: function(res) {
    //     console.log(JSON.stringify(res));
    //   }
    // });
  console.log(config);
    //分享给好友
    wx.onMenuShareAppMessage({
      title: config.title,
      desc: config.desc,
      link: config.link,
      imgUrl: config.imgUrl,
      success:function(res){
        console.log(1)
      },
      cancel:function(){
        console.log(2)
      },
      error:function(){
        console.log(3)
      }
    });
    //分享到朋友圈
    wx.onMenuShareTimeline({
      title: config.title,
      desc: config.desc,
      link: config.link,
      imgUrl: config.imgUrl,
      success: function(res) {
        console.log(1);
      },
      cancel: function() {
        console.log(2);
      },
      error: function() {
        console.log(3);
      }
    });
  });
}

let share = {
  getWeixincofig: getWeixincofig
};
export default share;